#include<iostream>
#include<string>
#include<pthread.h>
#include<unistd.h>
#include<cstdio>
#include<ctime>
#include<stdlib.h>
using namespace std;

//售票代码
class Ticket
{
private:
    int _tickets; //票数
    pthread_mutex_t _mtx;//原生线程库锁,系统级别   
public:
    Ticket()
    :_tickets(100)
    {
        pthread_mutex_init(&_mtx,nullptr);
    }

    bool GetTicket()
    {
      bool ret=true;
      pthread_mutex_lock(&_mtx); //加锁
      //加锁和解锁之间是临界区,线程每次进入临界区都需要先申请锁
      if(_tickets>0)
      {
        usleep(1000); //1s=1000ms 1ms=1000us
        cout<<"我是:"<<pthread_self()<<"我抢到的票是"<<_tickets<<endl;
        _tickets--;
      } 
      else{
        cout<<"票被抢空了！"<<endl; ret=false;
      } 
      pthread_mutex_unlock(&_mtx);//解锁
      return ret;
    }
    ~Ticket()
    {
        pthread_mutex_destroy(&_mtx);
    }
    
};


//线程要执行的函数
void* ThreadRoutine(void* args)
{
    Ticket* t=(Ticket*)args;
    while(true)
    {
        if(!t->GetTicket())//没票了break
        {
            break;
        }
    }

}

int main()
{
    Ticket* t=new Ticket();
    pthread_t tid[5];
    for(int i=0;i<5;i++)
    {
        int *id=new int(i);
        pthread_create(tid+i,nullptr,ThreadRoutine,(void*)t);
    }

    for(int i=0;i<5;i++)
    {
        pthread_join(tid[i],nullptr);
    }

    return 0;
}
